const Koa = require('koa')
let WebSocket = require("koa-websocket");

const cc = require('./conCtl')
const js = require('./jsCtl')
const pc = require('./projectCtl');
const db = require('./dbCtl');

// const result = {
//     code="",
//     msg="",
//     pushMoney="",
//     nick="",
//     headurl="",
//     count=""
// };

/* 实例化 WebSocket, 实例化储存所有上线文数组 并分配监听的端口 */
let app = WebSocket(new Koa());

app.listen(60110);

/* 实现简单的接发消息 */
app.ws.use(c => {
    /* 每打开一个连接就往 上线文数组中 添加一个上下文 */
    pc.ctxs[c.header['sec-websocket-key']] = c;
    c.websocket.on("message", async (message) => {
        cc.log(message);
        let msgArr = message.split('|');
        let pushType = msgArr[0];
        let pushAuctionid = msgArr[1];
        let pushOpenid = msgArr[2];
        let pushAuctionGoodsid = msgArr[3];

        //调用pc缓存,进行出价,出价成功后发送广播
        // let pcGoods = pc.storeAllAuction.auctionList[pushAuctionid].goods;

        let pcGoods = await db.model('t_auction_log').where('auction_goods_id=?', pushAuctionGoodsid).orderBy('dt desc').shift();
        //广播出价信息
        let result = {};
        if (pushType == 'push') {
            //出价保护期间,禁止重复出价
            if (pcGoods.dt && (new Date()).getTime() - new Date(pcGoods.dt).getTime() < 1000) {
                c.websocket.send('-1|出价失败');
            }
            let rate = await db.model('t_users').where('openid=?', pushOpenid).shift('', 'payment_rate');
            if (rate < 70)
                c.websocket.send('-1|请先缴纳保证金!');

            // let auction = pc.storeAllAuction.auctionList[c.request.body.auction_id];
            let goods = await db.model('t_auction_goods a').join('t_goods b on a.goods_id = b.id')
                .where('a.auction_goods_id=?', pushAuctionGoodsid)
                .shift();

            let log = await db.model('t_auction_log')
                .where('auction_goods_id=?', pushAuctionGoodsid)
                .orderBy('offer_id desc,dt desc')
                .shift();
            let price = 0;
            if (!js.isNullOrUndefined(log.offer_price)) {
                price = log.offer_price + goods.bid_increment;
            } else {
                //当起拍价等于0时,第一手竞拍价应为加价幅度;否则第一手竞价为起拍价
                if (goods.starting_price == 0) {
                    price = goods.bid_increment;
                } else {
                    price = goods.starting_price;
                }
            }
            await db.model('t_auction_log').insert({ auction_goods_id: pushAuctionGoodsid, offer_type: 1, offer_openid: pushOpenid, offer_price: price });
            let count = await db.model('t_auction_log').where('auction_goods_id=?', pushAuctionGoodsid).count();
            // pc.storeAllAuction.auctionList[pushAuctionid].goods.last_offer_time = (new Date()).getTime();
            let users = await db.model('t_users').where('openid=?', pushOpenid).shift();
            let curGoods = pc.storeAllAuction.auctionList[pushAuctionid].curGoods;
            for (let i = 0; i < curGoods.length; i++) {
                const element = curGoods[i];
                if (element.auction_goods_id == pushAuctionGoodsid) {
                    element.last_price = price;
                    element.list = { offer_type: 2, offer_openid: pushOpenid, offer_price: price, user: users.nick, headurl: users.headurl };
                    element.count = count;
                }
            }
            result = {
                code: 0,
                msg: '出价成功',
                pushMoney: price,
                nick: users.nick,
                headurl: users.headurl,
                count,
                auction_goods_id: pushAuctionGoodsid,
                state:2,
                openid:pushOpenid
            };
        } else if (pushType == 'svaha') {
            //出价保护期间,禁止重复出价
            if ((pcGoods.dt).getTime() && (new Date()).getTime() - (pcGoods.dt).getTime() < 1000) {
                c.websocket.send('-1|梭哈失败');
            }
            let rate = await db.model('t_users').where('openid=?', pushOpenid).shift('', 'payment_rate');
            if (rate < 70)
                c.websocket.send('-1|请先缴纳保证金!');
            let beipai = await db.model('t_auction_goods').where('auction_goods_id=?&&state=3', pushAuctionGoodsid).shift();
            cc.log(beipai);
            if (!js.isNullOrUndefined(beipai.state))
                c.websocket.send('-1|商品已被拍');
            let data1 = await db.model('t_auction_log')
                .where('auction_goods_id=?', pushAuctionGoodsid)
                .orderBy('dt desc')
                .shift();
            let data = await db.model('t_auction_goods a')
                .join('t_goods b on a.goods_id=b.id')
                .where('a.auction_goods_id=?', pushAuctionGoodsid)
                .field('b.svaha_price,b.bid_increment')
                .shift();
            if (!js.isNullOrUndefined(data1.offer_price)) {
                //有人出价
                //判断当前梭哈人的梭哈价小于最先出价人的出价,则梭哈人的价格为最新出价加该商品加价幅度
                if (data.svaha_price < data1.offer_price) {
                    data.svaha_price = data1.offer_price + data.bid_increment;
                }
            } else {
                //无人出价
                data.svaha_price = data.bid_increment;
            }

            //新增当前梭哈人出价纪录
            await db.model('t_auction_log')
                .insert({ auction_goods_id: pushAuctionGoodsid, offer_type: 1, offer_openid: pushOpenid, offer_price: data.svaha_price });
            //修改该竞拍商品的最终成交价以及中拍人ID、该竞拍活动的商品状态已结束
            await db.model('t_auction_goods')
                .where('auction_goods_id=?', pushAuctionGoodsid)
                .update({ final_price: data.svaha_price, winner_openid: pushOpenid, state: 3 });
            let count = await db.model('t_auction_log').where('auction_goods_id=?', pushAuctionGoodsid).count();
            // pc.storeAllAuction.auctionList[pushAuctionid].goods.last_offer_time = (new Date()).getTime();
            let users = await db.model('t_users').where('openid=?', pushOpenid).shift();
            // pc.storeAllAuction.auctionList[pushAuctionid].goods.last_offer_time = (new Date()).getTime();
            let curGoods = pc.storeAllAuction.auctionList[pushAuctionid].curGoods;
            for (let i = 0; i < curGoods.length; i++) {
                const element = curGoods[i];
                if (element.auction_goods_id == pushAuctionGoodsid) {
                    element.last_price = data.svaha_price;
                    element.list = { offer_type: 2, offer_openid: pushOpenid, offer_price: data.svaha_price, user: users.nick, headurl: users.headurl };
                    element.count = count;
                    element.state = 3;
                }
            }
            result = {
                code: 0,
                msg: '梭哈成功',
                pushMoney: data.svaha_price,
                nick: users.nick,
                headurl: users.headurl,
                count,
                auction_goods_id: pushAuctionGoodsid,
                state:3,
                openid:pushOpenid
            };
        }

        // if (!sendMsg) {
        //     c.websocket.send('通讯协议错误');
        //     return;
        // };
        for (let [key, value] of Object.entries(pc.ctxs)) {
            value.websocket.send(JSON.stringify(result));
        }
    });
    c.websocket.on("close", _ => {
        /* 连接关闭时, 清理 上下文数组, 防止报错 */
        delete pc.ctxs[c.header['sec-websocket-key']];
    });
});